
/*
This file is part of MJIN2.

Copyright (C) 2012-2013 Opensource Game Studio

This software is provided 'as-is', without any express or implied
warranty.  In no event will the authors be held liable for any damages
arising from the use of this software.

Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not
   claim that you wrote the original software. If you use this software
   in a product, an acknowledgment in the product documentation would be
   appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/

#include <mjin2/SequenceListener.h>
#include <mjin2/Timer.h>
#include <mjin2/priv/Sequence.h>

namespace mjin2
{
namespace priv
{

Sequence::Sequence(mjin2::Timer *timer) : mTimer(timer),
                                          mIsRunning(false),
                                          mSI(SEQUENCE_INTERPOLATION_NONE),
                                          mListener(0) { }

Sequence::~Sequence()
{
    stop();
}

void Sequence::addPoint(const SequencePoint &p, u32 reachTime)
{
    mPoints.push_back(Point(p, reachTime));
}

void Sequence::clear()
{
    mPoints.clear();
}

void Sequence::runInOneStep()
{
    if (mIsRunning || !mListener)
        return;
    mListener->onSequenceStart();
    auto it = --mPoints.end();
    mListener->onSequencePoint(it->p);
    mListener->onSequenceFinish();
}

void Sequence::setInterpolation(SEQUENCE_INTERPOLATION si)
{
    if (mIsRunning)
        return;
    mSI = si;
}

void Sequence::setListener(SequenceListener *listener)
{
    mListener = listener;
}

void Sequence::start()
{
    prepare();
    if (mIsRunning || !canContinue())
        return;
    mTimer->addListener(this, 0);
    mIsRunning = true;
    mElapsedSinceLastPoint = 0;
    if (mListener)
    {
        mListener->onSequenceStart();
        // Report the first point.
        auto it = mPoints.begin();
        mListener->onSequencePoint(it->p);
    }
}

void Sequence::stop()
{
    if (!mIsRunning)
        return;
    mTimer->removeListener(this);
    mIsRunning = false;
    if (mListener)
    {
        // Report the last point.
        auto it = --mPoints.end();
        mListener->onSequencePoint(it->p);
        mListener->onSequenceFinish();
    }
}

bool Sequence::canContinue()
{
    return (mLastPointID - mCurrentPointID) > 0;
}

float Sequence::linearInterpolate(float p1, float p2, float t)
{
    return p1 + t * (p2 - p1);
}

SequencePoint Sequence::linearInterpolate(const SequencePoint &p1,
                                          const SequencePoint &p2,
                                          float t)
{
    SequencePoint p;
    for (u32 i = 0; i < p1.size(); ++i)
        p.push_back(linearInterpolate(p1[i], p2[i], t));
    return p;
}

void Sequence::onTimerTick(u32 elapsedMilliseconds)
{
    mElapsedSinceLastPoint += elapsedMilliseconds;
    u32 nextPointRT = mAllPoints[mCurrentPointID + 1].rt;
    while (mElapsedSinceLastPoint > nextPointRT)
    {
        mElapsedSinceLastPoint -= nextPointRT;
        ++mCurrentPointID;
        nextPointRT = mAllPoints[mCurrentPointID + 1].rt;
    }
    if (canContinue())
    {
        float t = static_cast<float>(mElapsedSinceLastPoint) /
                  static_cast<float>(nextPointRT);
        SequencePoint p;
        switch (mSI)
        {
            case SEQUENCE_INTERPOLATION_NONE:
                p = mAllPoints[mCurrentPointID].p;
                break;
            case SEQUENCE_INTERPOLATION_LINEAR:
                p = linearInterpolate(mAllPoints[mCurrentPointID].p,
                                      mAllPoints[mCurrentPointID + 1].p, 
                                      t);
                break;
            case SEQUENCE_INTERPOLATION_SPLINE:
                p = splineInterpolate(mAllPoints[mCurrentPointID - 1].p,
                                      mAllPoints[mCurrentPointID].p,
                                      mAllPoints[mCurrentPointID + 1].p,
                                      mAllPoints[mCurrentPointID + 2].p,
                                      t);
                break;
        }
        if (mListener)
            mListener->onSequencePoint(p);
    }
    else
        stop();
}
        
void Sequence::prepare()
{
    mAllPoints = mPoints;
    // Additional starting and ending points for spline. Doesn't hurt others.
    mAllPoints.insert(mAllPoints.begin(), mPoints[0]);
    mAllPoints.push_back(mPoints[mPoints.size() - 1]);
    // Limits.
    mCurrentPointID = 1;
    mLastPointID = mAllPoints.size() - 2;
}

float Sequence::splineInterpolate(float p0,
                                  float p1,
                                  float p2,
                                  float p3,
                                  float t)
{
    // Catmull-Rom spline.
    // Formula from: http://www.mvps.org/directx/articles/catmull/
    return 0.5 * ((2.0 * p1) +
                  (-p0 + p2) * t +
                  (2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * t * t +
                  (-p0 + 3.0 * p1 - 3.0 * p2 + p3) * t * t * t);
}

SequencePoint Sequence::splineInterpolate(const SequencePoint &p0,
                                          const SequencePoint &p1,
                                          const SequencePoint &p2,
                                          const SequencePoint &p3,
                                          float t)
{
    SequencePoint p;
    for (u32 i = 0; i < p1.size(); ++i)
        p.push_back(splineInterpolate(p0[i], p1[i], p2[i], p3[i], t));
    return p;
}

} // namespace priv
} // namespace mjin2

